package libs

import (
	"exercise/common/constant"
	"time"
)

// JsonTime 时间转换
type JsonTime time.Time

func (j JsonTime) MarshalJSON() ([]byte, error) {
	return []byte(`"` + time.Time(j).Format(constant.TimestampTemplate) + `"`), nil
}

// TimestampToDate 时间戳转换成指定格式的日期
func TimestampToDate(timestamp int64, template string) string {
	if template == "" {
		template = constant.TimestampTemplate
	}
	tm := time.Unix(timestamp, 0)
	return tm.Format(template)
}

// DateToTimestamp 日期转换成时间戳
func DateToTimestamp(date string, template string) int64 {
	local, _ := time.LoadLocation("Local")
	if template == "" {
		template = constant.TimestampTemplate
	}
	dt, _ := time.ParseInLocation(template, date, local)
	return dt.Unix()
}

// CurrentTime  当前时间戳
func CurrentTime() int64 {
	return time.Now().Unix()
}

// SomedayStartTime 某天开始时间戳
func SomedayStartTime(i int) int64 {
	currentTime := time.Now().AddDate(0, 0, i)
	return time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location()).Unix()
}

// SomedayEndTime  某天结束时间戳
func SomedayEndTime(i int) int64 {
	currentTime := time.Now().AddDate(0, 0, i)
	return time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location()).Unix()
}

// JetLagTime  指定时间与当前时间的时间差
func JetLagTime(i int, h int, m int, s int) (l int64) {
	start := CurrentTime()
	currentTime := time.Now().AddDate(0, 0, i)
	end := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), h, m, s, 0, currentTime.Location()).Unix()
	l = end - start
	return
}
